
package com.scalar.chiptrack.sales.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.ClientInfo;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.sales.SalesRep;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.forms.AddNewSalesRepForm;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;


public class AddNewSalesRepAction extends ChipTrackAction {

    private static final String ACTION_NAME = "/addNewSalesRep.do" ;

    private ArrayList allsalesreps = new ArrayList();
    private String salesrep = null;

    public ActionForward execute (ActionMapping mapping,
                                      ActionForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response)
                                     throws Exception {

        HttpSession session = request.getSession();
        AddNewSalesRepForm addNewSalesRepForm = ( AddNewSalesRepForm )form;


             User user = (User)session.getAttribute (SessionKeys.USER_KEY);

             if (user == null)
             {
                session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString());
                return (mapping.findForward ("login"));
             }


		HashMap errors = new HashMap();
		request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);

		HashMap info = new HashMap();
		request.setAttribute (SessionKeys.INFO_MESSAGES, info);


		AddNewSalesRepForm addsalespersonform=(AddNewSalesRepForm) form;
		String action = request.getParameter("action");
		int customerId = Integer.parseInt(request.getParameter("customerId"));

		request.setAttribute("salesRepss",CustomerDAO.getAllSalesRepsWithActions(customerId));
		if ("disable".equalsIgnoreCase(request.getParameter("salesRepstatus")) == true)
		{
			String salesRepToDelete = request.getParameter("salesRep");

			if ((salesRepToDelete != null) && (salesRepToDelete.trim().length() != 0))
			{
				try {

					CustomerDAO.deleteSalesRep( salesRepToDelete , customerId );
					info.put (salesRepToDelete + " has been disabled", null);
				}
				catch (ScalarException se)
				{
					se.printStackTrace ();
					errors.put ("Internal Server Error", "Could not delete \"" + salesRepToDelete + "\"");
				}
			}
		}

		else if ("activate".equalsIgnoreCase(request.getParameter("salesRepstatus")) == true)
		{
		     String salesRepToActivate = request.getParameter("salesRep");
		  if ((salesRepToActivate != null) && (salesRepToActivate.trim().length() != 0))
		  {
		    try
		    {
			  CustomerDAO.activateSalesRep ( salesRepToActivate , customerId );
		      info.put (salesRepToActivate + " has been activated", null);
		    }
		    catch (ScalarException se)
		    {
		      se.printStackTrace ();
		      errors.put ("Internal Server Error", "Could not activate \"" + salesRepToActivate + "\"");
		    }
		  }
		}

		if("insertSalesRep".equalsIgnoreCase(action))
		{

			//salesrep = request.getParameter("newSalesRep");
            salesrep = addNewSalesRepForm.getNewSalesRep();
			boolean success = false;
			boolean temp = false;

            if( ( salesrep == null ) || ( salesrep.trim().length() == 0 ) ) {
				errors.put ( ERROR_CUSTOMER_INVALID_REPRESENTATIVE, null );
				return (mapping.findForward ("success"));
			}

			allsalesreps = CustomerDAO.getAllSalesRepsWithActions(customerId);
			int allsalesrepssSize = allsalesreps.size();
			SalesRep  salesRep = new  SalesRep();

			for (int j=0; j<allsalesrepssSize; j++)
			{
				salesRep =(SalesRep)allsalesreps.get(j);
				String salesrepname = salesRep.getSalesRep();
				if( (salesrep != null) && (salesrepname != null) )
				{
					if (salesrep.trim().equalsIgnoreCase(salesrepname))
					{
						temp= true;
						break;
					}
				}
			}//for end

			if (temp == true) {
				errors.put ( salesrep +" " + ERROR_CUSTOMER_REP_ALREADY_EXISTS, null );
			} else{
                try {
                    CustomerDAO.insertSalesRep (null, salesrep, customerId);
                    ClientInfo clientInfo = new ClientInfo();
                    clientInfo = UserDAO.getClientAddressInfo(  );
                    addNewSalesRepForm.setNewSalesRep("");
                    String salesRepLabel = null;
                    try
                    {
                        salesRepLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesRep.Name" );
                        if ( salesRepLabel == null )
                        {
                            salesRepLabel = Labels.DEFAULT_REPRESENTATIVE;
                        }
                    }
                    catch ( NullPointerException e )
                    {
                        salesRepLabel  = Labels.DEFAULT_REPRESENTATIVE;
                    }
                    info.put ( salesRepLabel+" saved successfully", null );
                    success = true;
                }
                catch (ScalarException se) {
                    errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                    se.printStackTrace();
                }
            }
		}
        request.setAttribute("salesReps",CustomerDAO.getAllSalesRepsWithActions(customerId));
        return (mapping.findForward ("success"));
    }

}
